import React from 'react';
import { Form, Icon, Divider, message, Spin } from 'antd';
import { history } from 'umi'
import { isMoment } from 'moment';
import { useRequest } from '@/hooks';
import BackgroundForm from './BackgroundForm';
import { updateBackgroundRec, addBackgroundRec } from '../service';
import { NOTICE_TYPE } from '../../dictionary';
import styles from './index.less';
import { backgroundTypeMap, changeNumToCharacter, feedbackStateInfo } from '../utils';

const EditableDetailForm = ({
    bgCompanyList,
    relateTypeList,
    isDetailItem = false,
    onSave,
    employId,
    candidateId,
    data = {},
    index,
    form,
    formItemLayout,
    isAddForm,
    count,
    setShowNewForm,
    setCount,
    recordList
}) => {
    // const [isDetail, setIsDetail] = React.useState(true);
    const [isDetail, setIsDetail] = React.useState(isDetailItem);

    const goToNoticePage = (id, params) => {
        const pathname = '/office/personnelManagement/recruitment/candidate/noticeBackground';
        const query = {
            backgroundId: id,
            noticeType: NOTICE_TYPE.BACKGROUND,
            email: params.organizationEmail,
            candidateId: params.candidateId,
            contactId: 1 // 目标页面要求值随意填，加上这个字段即可
        };
        history.push({
            pathname,
            query
        });
    };

    const { run: updateRec, loading: loadingUpdate } = useRequest(updateBackgroundRec, {
        manual: true,
        formatResult: res => {
            if (res) {
                const { code, msg } = res;
                if (code === 10000) {
                    message.success('修改成功！');
                    setCount(count + 1);
                    setIsDetail(true);
                    return data;
                }
                message.error(msg);
            }
            return undefined;
        },
        onSuccess: (res, [params]) => {
            if (params.feedbackState === 0) {
                goToNoticePage(params.id, params);
            }
        }
    });
    const { run: addRec, loading: loadingAdd } = useRequest(addBackgroundRec, {
        manual: true,
        formatResult: res => {
            if (res) {
                const { code, msg } = res;
                if (code === 10000) {
                    message.success('保存成功！');
                    if (onSave) {
                        onSave();
                    }
                    setCount(count + 1);
                    // setIsDetail(true);
                    return res.data;
                }
                message.error(msg);
            }
            return undefined;
        },
        onSuccess: (id, [params]) => {
            if (params.feedbackState === 0 && id) {
                goToNoticePage(id, params);
            }
        }
    });

    const loading = loadingUpdate || loadingAdd;

    const getCompareInfo = obj => {
        const compareKeys = [
            'backgroundType',
            'objectName',
            'objectContactType',
            'objectContactInfo',
            'organizationName'
        ];
        return compareKeys.reduce((pre, cur) => `${pre}-${obj[cur]}`, '');
    };

    const handleSave = () => {
        form.validateFields(async (err, values) => {
            if (!err) {
                const result = Object.keys(values).reduce((prev, curr) => {
                    const newPrev = { ...prev };
                    newPrev[curr.split('-')[0]] = isMoment(values[curr])
                        ? values[curr].format('YYYY-MM-DD HH:mm:00')
                        : values[curr];
                    return newPrev;
                }, {});

                const resultCompareInfo = getCompareInfo(result);
                const compareRecordList = data.id ? recordList.filter(item => item.id !== data.id) : recordList;
                const isDuplicate = compareRecordList.some(item => resultCompareInfo === getCompareInfo(item));
                if (isDuplicate) {
                    message.error('保存失败，存在重复背调（背调公司、对象姓名、联系方式均相同）');
                    return;
                }
                if (data.id) {
                    const extra = {};
                    if (result.feedbackState === feedbackStateInfo[0].value) {
                        // 如果是把人事代填改成机构自主反馈，则把人事填的结论和附件清掉
                        extra.backgroundTime = '';
                        extra.evaluateRemark = '';
                        extra.uploadFileUrl = '';
                    }
                    updateRec({ ...result, candidateId: Number(candidateId), id: data.id, ...extra });
                } else {
                    addRec({ ...result, employId: Number(employId), candidateId: Number(candidateId) });
                }
            }
        });
    };

    const { backgroundType, feedbackState = 0 } = (() => {
        const values = form.getFieldsValue();
        const result = {};
        Object.keys(values).forEach(item => {
            if (item.split('-')[0] === 'backgroundType') {
                result.backgroundType = values[item];
            }
            if (item.split('-')[0] === 'feedbackState') {
                result.feedbackState = values[item];
            }
        });
        return result;
    })();

    const isAlert = !data?.evaluateRemark && isDetail && data?.backgroundType === 1;

    return (
        <div className={styles.detailFormWrap}>
            {/* {needDivider && <Divider style={{ background: '#ededed' }} />} */}
            <div className={styles.title}>
                <div className={styles.leftTitle}>
                    {data.backgroundType
                        ? `背调${changeNumToCharacter(index + 1)}（${backgroundTypeMap[data.backgroundType]}）`
                        : `背调${changeNumToCharacter(index + 1)}`}
                </div>
                <div className={styles.rightIcon}>
                    {/* 是否能编辑统一用modifyFlag判断， 值是0和1都要可编辑，如果是0，表示表单是候选人提交上来的，只能编辑评价。
                    如果是1，则是自己添加的表单，可编辑所有字段 */}
                    {/* {isDetail && data.modifyFlag === 0 && ( */}
                    {/* 如果背调类型是第三方机构且背调反馈方式是机构自主反馈则不能编辑 */}
                    {isDetail &&
                        !(data.backgroundType === 2 && data.feedbackState === feedbackStateInfo[0].value) &&
                        !isAlert && (
                            <Icon
                                className={styles.icon}
                                type="edit"
                                onClick={() => {
                                    setIsDetail(false);
                                    // setIsEditing(true);
                                }}
                            ></Icon>
                        )}
                    {!isDetail && (
                        <>
                            {/* {isAddForm && backgroundType === 2 && feedbackState === 0 && ( */}
                            {backgroundType === 2 && feedbackState === 0 && (
                                <span className={styles.helpText}>保存成功后将打开通知背调机构页面</span>
                            )}
                            <Icon
                                className={styles.icon}
                                type="close"
                                onClick={() => {
                                    if (isDetailItem) {
                                        // 编辑已有数据，点击后退出编辑
                                        setIsDetail(true);
                                        form.resetFields();
                                    } else {
                                        // 新表单点击后关闭该表单
                                        setShowNewForm(false);
                                    }
                                }}
                            ></Icon>
                            <Divider type="vertical" style={{ margin: '0 16px' }} />
                            {!loading ? (
                                <Icon className={styles.icon} type="check" onClick={handleSave}></Icon>
                            ) : (
                                <Spin />
                            )}
                        </>
                    )}
                </div>
            </div>
            <Form {...formItemLayout} className={styles.formWrap}>
                <BackgroundForm
                    isAddForm={isAddForm}
                    form={form}
                    isDetail={isDetail}
                    initialFormInfo={data}
                    bgCompanyList={bgCompanyList}
                    relateTypeList={relateTypeList}
                    setIsDetail={setIsDetail}
                    isAlert={isAlert}
                />
            </Form>
        </div>
    );
};

export default Form.create()(EditableDetailForm);
